﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

namespace Estimate.Common.Estimate
{
    /// <summary>
    /// XML序列与反序列化
    /// </summary>
  public  class XmlSerialization
    {
        // OBJECT -> XML 
      public static void SaveXml(string filePath, object obj)
      {
          SaveXml(filePath, obj, obj.GetType());
      }

      public static void SaveXml(string filePath, object obj, System.Type type)
      {
          using (System.IO.StreamWriter writer = new System.IO.StreamWriter(filePath))
          {
              System.Xml.Serialization.XmlSerializer xs = new System.Xml.Serialization.XmlSerializer(type);
              xs.Serialize(writer, obj);
              writer.Close();
          }
      }

        // XML -> OBJECT 
        public static object LoadXml(string filePath, System.Type type)
        {
            if (!System.IO.File.Exists(filePath)) return null;
            using (System.IO.StreamReader reader = new System.IO.StreamReader(filePath))
            {
                System.Xml.Serialization.XmlSerializer xs = new System.Xml.Serialization.XmlSerializer(type);
                object obj = xs.Deserialize(reader); 
                reader.Close();
                return obj;
            }
        }
    }
}
